package bb.lanxing.activity.team;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.mylhyl.circledialog.CircleDialog;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.routebook.RouteBookChooseActivity;
import bb.lanxing.activity.sport.SportActivity;
import bb.lanxing.adapter.discover.BbsImageCreateAdapter;
import bb.lanxing.adapter.team.TeamImageCreateAdapter;
import bb.lanxing.ali.behavior.AppBehavior;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.City;
import bb.lanxing.model.database.Event;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.network.OkUploadListener;
import bb.lanxing.util.BiCiCoorConverter;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.DateUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.Validator;
import bb.lanxing.util.image.GlideEngine;
import bb.lanxing.view.BiciAlertDialogBuilder;
import gov.nist.core.Separators;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class TeamCreateActivity extends BaseActivity {
    private static final int REQUEST_START_ADDRESS = 100;
    private static final int REQUEST_LUSHU = 10;

    private FrameLayout photoFrameLayout;
    private LinearLayout photoHintLayout;

    private ImageView addImage;
    private TextView imageHint;
    private RecyclerView imageRecyclerView;
    private TeamImageCreateAdapter teamImageCreateAdapter = new TeamImageCreateAdapter();
    private ArrayList<String> imageList = new ArrayList<>();
    private EditText distanceEt;
    private TextView lushuTv;
    private TextView titleNumText;
    private TextView startTimeTv;
    private TextView endTimeTv;
    private TextView addressTv;
    private TextView gradeTv;
    private TextView introduceNumTv;

    private Event event = Event.getLastUncommit();
    private boolean isFirstCreate = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_create);

        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());
        photoFrameLayout = findViewById(R.id.fl_photo);
        photoHintLayout = findViewById(R.id.ll_photo_hint);
        addImage = findViewById(R.id.add_image);
        photoFrameLayout.setOnClickListener(v -> PictureSelector.create(this).openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(1)
                .forResult(new OnResultCallbackListener<>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        event.setPhotoUrl(result.get(0).getRealPath());
                        setImage();
                    }

                    @Override
                    public void onCancel() {
                    }
                }));

        imageHint = findViewById(R.id.imageHint);
        imageRecyclerView = findViewById(R.id.imageRecyclerView);
        imageRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        teamImageCreateAdapter.updateData(imageList);
        teamImageCreateAdapter.setOnItemClickListener(position -> {
            if (BbsImageCreateAdapter.TYPE_ADD == teamImageCreateAdapter.getItemViewType(position)) {
                int newNum = 4 - imageList.size();
                PictureSelector.create(this).openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(newNum)
                        .forResult(new OnResultCallbackListener<>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                for (LocalMedia localMedia : result) {
                                    imageList.add(localMedia.getRealPath());
                                }
                                setPhotoUrl();
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            } else {
                Intent intent = new Intent(this, LargeImageActivity.class);
                intent.putStringArrayListExtra("images", imageList);
                intent.putExtra("currentImage", position);
                startActivity(intent);
            }
        });
        teamImageCreateAdapter.setRemoveListener(position -> {
            imageList.remove(position);
            setPhotoUrl();
        });
        imageRecyclerView.setAdapter(teamImageCreateAdapter);

        EditText titleEditText = findViewById(R.id.title_et);
        titleEditText.addTextChangedListener(new MyTextWatcher(1));
        titleNumText = findViewById(R.id.title_num);

        startTimeTv = findViewById(R.id.start_time_tv);
        startTimeTv.setOnClickListener(v -> onStartTimeClick());
        endTimeTv = findViewById(R.id.end_time_tv);
        endTimeTv.setOnClickListener(v -> onEndTimeClick());

        addressTv = findViewById(R.id.address_tv);
        addressTv.setOnClickListener(v -> {
            Intent intent = new Intent(this, TeamCreateLocationActivity.class);
            if (event.getStartAddr() != null) {
                intent.putExtra("lat", event.getStartLat());
                intent.putExtra("lng", event.getStartLng());
            }
            startActivityForResult(intent, REQUEST_START_ADDRESS);
        });

        gradeTv = findViewById(R.id.grade_tv);
        gradeTv.setOnClickListener(v -> onLevelClick());

        lushuTv = findViewById(R.id.lushu_tv);
        lushuTv.setOnClickListener(v -> onLushuClick());

        distanceEt = findViewById(R.id.distance_et);
        distanceEt.addTextChangedListener(new MyTextWatcher(2));
        EditText introduceEt = findViewById(R.id.introduce_et);
        introduceEt.addTextChangedListener(new MyTextWatcher(3));
        introduceNumTv = findViewById(R.id.introduce_tv_num);

        EditText priceEt = findViewById(R.id.price_et);
        priceEt.addTextChangedListener(new MyTextWatcher(4));
        EditText countEt = findViewById(R.id.count_et);
        countEt.addTextChangedListener(new MyTextWatcher(5));
        EditText phoneEt = findViewById(R.id.phone_et);
        phoneEt.addTextChangedListener(new MyTextWatcher(6));

        Switch needApproveSwitch = findViewById(R.id.needApproveSwitch);
        needApproveSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                event.setOwnerApprove(1);
            } else {
                event.setOwnerApprove(0);
            }
        });

        TextView commitBtn = findViewById(R.id.commitBtn);
        commitBtn.setOnClickListener(v -> onCommitClick());

        if (event == null) {
            event = new Event();
            event.setLevel(0);
            event.setUserId(SharedManager.getInstance().getUserId());
            event.setTemp(true);
        }

        if (!TextUtils.isEmpty(event.getPhotoUrl())) {
            setImage();
        }
        titleEditText.setText(event.getTitle());
        if (event.getStartTime() > 0) {
            startTimeTv.setText(DateUtil.format(event.getStartTime(), 6));
        }
        if (event.getEndTime() > 0) {
            endTimeTv.setText(DateUtil.format(event.getEndTime(), 6));
        }

        addressTv.setText(event.getStartAddr());
        gradeTv.setText(Event.getLevelName(this, event.getLevel()));
        distanceEt.setText(CommonUtil.getKMDistance(event.getDistance()));

        introduceEt.setText(event.getDescription());

        priceEt.setText(CommonUtil.getKMDistance(event.getCost()));
        String str = event.getMemberLimit() + "";
        if (event.getMemberLimit() < 2) {
            str = "50";
        }
        countEt.setText(str);
        if (TextUtils.isEmpty(event.getPhoneNumber())) {
            String phone = App.getContext().getSigninUser().getPhone();
            if (!TextUtils.isEmpty(phone)) {
                phoneEt.setText(phone);
            }
        } else {
            phoneEt.setText(event.getPhoneNumber());
        }
        if (event.getOwnerApprove() == 1) {
            isFirstCreate = false;
            needApproveSwitch.setChecked(true);
        } else {
            needApproveSwitch.setChecked(false);
        }
    }

    private void setImage() {
        String[] photoUrls = event.getPhotoUrl().split(";");
        Glide.with(this).load(photoUrls[0]).into(addImage);
        for (String photoUrl : photoUrls) {
            imageList.add(photoUrl);
        }
        teamImageCreateAdapter.updateData(imageList);
        imageHint.setVisibility(View.VISIBLE);
        imageRecyclerView.setVisibility(View.VISIBLE);
        // addImage.setClickable(false);
        photoHintLayout.setVisibility(View.GONE);
        photoFrameLayout.setClickable(false);
    }

    private void setPhotoUrl() {
        teamImageCreateAdapter.updateData(imageList);
        String url = "";
        if (imageList.isEmpty()) {
            imageHint.setVisibility(View.GONE);
            imageRecyclerView.setVisibility(View.GONE);
            addImage.setImageResource(R.drawable.ic_preview);
            // addImage.setClickable(true);
            photoFrameLayout.setClickable(true);
            photoHintLayout.setVisibility(View.VISIBLE);
        } else {
            for (String imageString : imageList) {
                url += imageString + ";";
            }
            url = url.substring(0, url.length() - 1);
            Glide.with(this).load(imageList.get(0)).into(addImage);
        }
        event.setPhotoUrl(url);
    }

    private void onStartTimeClick() {
        long startTime = event.getStartTime();
        Calendar calendar = Calendar.getInstance();
        if (startTime > 0) {
            calendar.setTimeInMillis(startTime);
        }
        showDateTimePick(calendar, new Date().getTime(), true);
    }

    private void onEndTimeClick() {
        long startTime = event.getStartTime();
        long endTime = event.getEndTime();
        long time = new Date().getTime();
        Calendar calendar = Calendar.getInstance();
        if (endTime > 0) {
            calendar.setTimeInMillis(endTime);
        } else if (startTime > 0) {
            calendar.setTimeInMillis(startTime);
            calendar.set(11, 0);
            calendar.set(12, 0);
            calendar.set(13, 0);
            time = calendar.getTimeInMillis();
            calendar.setTimeInMillis(startTime);
        }
        showDateTimePick(calendar, time, false);
    }

    private void showDateTimePick(final Calendar calendar, long minDate, final boolean isStart) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.date_time_picker_view, (ViewGroup) null);
        final DatePicker datePicker = inflate.findViewById(R.id.datePicker);
        datePicker.setMinDate(minDate);
        datePicker.updateDate(calendar.get(1), calendar.get(2), calendar.get(5));
        final TimePicker timePicker = inflate.findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setHour(calendar.get(11));
        timePicker.setMinute(calendar.get(12));
        new BiciAlertDialogBuilder(this).setView(inflate).setPositiveButton(R.string.dialog_btn_ok, (dialog, which) -> {
            calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getHour(),
                    timePicker.getMinute());
            if (isStart) {
                if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
                    App.getContext().showMessage("开始时间要晚于当前时间哦");
                    return;
                }
                // if (calendar.getTimeInMillis() >= event.getEndTime()) {
                // App.getContext().showMessage("开始时间要早于结束时间哦");
                // return;
                // }
                event.setStartTime(calendar.getTimeInMillis());
                startTimeTv.setText(DateUtil.format(calendar.getTimeInMillis(), 6));
            } else {
                if (calendar.getTimeInMillis() <= event.getStartTime()) {
                    App.getContext().showMessage("结束时间要晚于开始时间哦");
                    return;
                }
                event.setEndTime(calendar.getTimeInMillis());
                endTimeTv.setText(DateUtil.format(calendar.getTimeInMillis(), 6));
            }
        }).setNegativeButton(R.string.dialog_btn_cancel, (dialog, which) -> dialog.cancel()).show();
    }

    private void onLevelClick() {
        final String[] stringArray = getResources().getStringArray(R.array.event_level);
        new CircleDialog.Builder().setItems(stringArray, (parent, view, position, id) -> {
            event.setLevel(position);
            gradeTv.setText(stringArray[position]);
            return true;
        }).show(getSupportFragmentManager());
    }

    private void onLushuClick() {
        Intent intent = new Intent(this, RouteBookChooseActivity.class);
        intent.putExtra(SportActivity.EXTRA_LUSHU_ID, event.getLushuId());
        intent.putExtra(RouteBookChooseActivity.INTENT_TYPE, true);
        startActivityForResult(intent, REQUEST_LUSHU);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_START_ADDRESS && data != null) {
            event.setStartAddr(data.getStringExtra("StartAddr"));
            LatLng curLatLngWithMP = SharedManager.getInstance().getCurLatLngWithMP();
            LatLng baidu2Earth =
                    BiCiCoorConverter.baidu2Earth(new LatLng(data.getDoubleExtra("lat", curLatLngWithMP.latitude),
                            data.getDoubleExtra("lng", curLatLngWithMP.longitude)));
            event.setStartLat(baidu2Earth.latitude);
            event.setStartLng(baidu2Earth.longitude);
            if (TextUtils.isEmpty(data.getStringExtra("CityId"))) {
                event.setCityId(City.getCityIdByName(SharedManager.getInstance().getCurCityWithMP()));
            } else {
                event.setCityId(City.getCityIdByName(data.getStringExtra("CityId")));
            }
            Log.d("get biciLatlng event = " + event.getStartAddr() + " , " + event.getStartLat() + " , "
                    + event.getCityId());
            addressTv.setText(event.getStartAddr());
        }
        if (requestCode == REQUEST_LUSHU && resultCode == Activity.RESULT_OK) {
            long longExtra = data.getLongExtra(SportActivity.EXTRA_LUSHU_ID, 0L);
            if (longExtra > 0) {
                RouteBook byServerId = RouteBook.getByServerId(longExtra);
                if (byServerId != null) {
                    distanceEt.setText(String.format("%.2f", byServerId.getDistance() / 1000.0d));
                    lushuTv.setText(Separators.POUND + longExtra);
                    event.setLushuId(longExtra);
                    event.setLushuUuid(byServerId.getUuid());
                    event.setLushuTitle(byServerId.getTitle());
                    event.setDistance(byServerId.getDistance());
                } else {
                    distanceEt.setText("");
                    lushuTv.setText("");
                    event.setLushuId(-1L);
                    event.setLushuUuid("");
                    event.setLushuTitle("");
                    event.setDistance(0.0);
                }
            }
        }
    }

    private void onCommitClick() {
        if (event.isTemp()) {
            event.save();
        }
        if (validDatas(true)) {
            postEvent(event, imageList);
        }
    }

    private boolean validDatas(boolean showToast) {
        if (TextUtils.isEmpty(event.getPhotoUrl())) {
            if (showToast) {
                App.getContext().showMessage(R.string.team_add_new_event_photo_tips);
            }
            return false;
        } else if (TextUtils.isEmpty(event.getTitle())) {
            if (showToast) {
                App.getContext().showMessage(R.string.event_create_verify_title_null);
            }
            return false;
        } else if (event.getStartTime() == 0) {
            if (showToast) {
                App.getContext().showMessage(R.string.event_create_verify_input_start_time);
            }
            return false;
        } else if (event.getEndTime() == 0) {
            if (showToast) {
                App.getContext().showMessage(R.string.event_create_verify_input_stop_time);
            }
            return false;
        } else if (TextUtils.isEmpty(event.getStartAddr())) {
            if (showToast) {
                App.getContext().showMessage(R.string.event_create_verify_address_null);
            }
            return false;
        } else if (event.getDistance() == 0) {
            if (showToast) {
                App.getContext().showMessage(R.string.team_add_new_event_mileage_not_empty_tips);
            }
            return false;
        } else if (TextUtils.isEmpty(event.getDescription())) {
            if (showToast) {
                App.getContext().showMessage(R.string.event_create_verify_desc_null);
            }
            return false;
        } else if (event.getMemberLimit() == 0) {
            if (showToast) {
                App.getContext().showMessage(R.string.team_add_new_event_person_not_empty_tips);
            }
            return false;
        } else if (!Validator.isPhoneNumber(event.getPhoneNumber())) {
            if (showToast) {
                App.getContext().showMessage(R.string.event_create_verify_input_valid_phone);
            }
            return false;
        } else {
            return true;
        }
    }

    private void postEvent(final Event event, List<String> images) {
        showLoadingDialog(R.string.event_create_toast_creating, true, null);
        event.save();
        updateImages(event.getEventId(), images).flatMap((Func1<String, Observable<String>>) s -> {
            JSONArray jarr = new JSONArray();
            String[] args = s.split(";");
            try {
                for (int i = 0; args != null && i < args.length; i++) {
                    JSONObject jsonObject = new JSONObject(args[i].toString());
                    int code = jsonObject.getInt("code");
                    if (200 == code) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("fileInfo");
                        Long userFileId = jsonObject1.getLong("userFileId");
                        JSONObject j1 = new JSONObject();
                        j1.put("fileId", userFileId);
                        j1.put("userId", App.getContext().getUserId());
                        jarr.put(j1);
                    }
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            event.setPhotoUrl(jarr.toString());
            return Observable.create(new NetSubscribe(MyHttpClient.createActivity(event)));
        }).flatMap((Func1<String, Observable<Long>>) s -> {
            try {
                JSONObject jsonObject = new JSONObject(s);
                int code = jsonObject.getInt("code");
                if (200 == code) {
                    event.delete();
                    event.setTemp(false);
                    JSONObject jsonObject1 = jsonObject.getJSONObject("respTencentIM");
                    event.setTencentImGroupId(jsonObject1.getString("groupId"));
                    event.save();
                    return Observable.just(event.getEventId());
                } else {
                    String msg = jsonObject.getString("msg");
                    App.getContext().showMessage(msg);
                    return null;
                }
            } catch (JSONException e) {
                return Observable.error(e);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                onCreateFailed(e instanceof NetSubscribe.ApiException ? e.getMessage() : null);
                dismissLoadingDialog();
            }

            @Override
            public void onNext(Long activityId) {
                onCreateSuccessful(activityId);
                dismissLoadingDialog();
            }
        });
    }

    private void onCreateFailed(String mesg) {
        if (TextUtils.isEmpty(mesg)) {
            mesg = getString(R.string.event_create_toast_create_failure);
        }
        toast(mesg);
    }

    private void onCreateSuccessful(Long activityId) {
        AppBehavior.route().create().item(String.valueOf(activityId)).submit();
        App.getContext().showMessage(R.string.event_create_toast_create_successful);
        setResult(4096);
        finish();
    }

    private Observable<String> updateImages(long eventId, List<String> images) {
        if (images == null || images.isEmpty()) {
            return Observable.just("");
        }
        return Observable.just(images).flatMap((Func1<List<String>, Observable<String>>) images2 -> {
            if (images2 == null || images2.isEmpty()) {
                return Observable.just(null);
            }
            ArrayList arrayList = new ArrayList();
            for (String image : images2) {
                if (!image.startsWith("http://") && !image.startsWith("https://")) {
                    arrayList.add(updateImage(eventId, image));
                }
            }
            return Observable.zip(arrayList, args -> {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; args != null && i < args.length; i++) {
                    sb.append(args[i].toString());
                    if (i < args.length - 1) {
                        sb.append(";");
                    }
                }
                return sb.toString();
            });
        });
    }

    private Observable<String> updateImage(long eventId, String fileName) {
        String md5 = CommonUtil.getMD5(new File(fileName));
        return Observable
                .create(new NetSubscribe(MyHttpClient.uploadEventPic(eventId, fileName, md5, new OkUploadListener() {
                    @Override
                    public void upload(long j, long j2) {
                    }
                })));
    }

    @Override
    public void onBackPressed() {
        if (event.isTemp()) {
            if (isFirstCreate) {
                event.save();
            } else {
                ContentValues contentValues = new ContentValues();
                contentValues.put("ownerApprove", event.getOwnerApprove());
                event.update(contentValues);
            }
        }
        super.onBackPressed();
    }

    private class MyTextWatcher implements TextWatcher {
        private int index;

        public MyTextWatcher(int index) {
            this.index = index;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int length = s.toString().length();
            try {
                switch (index) {
                case 1:
                    titleNumText.setText("" + (30 - length));
                    event.setTitle(s.toString());
                    break;
                case 2:
                    event.setDistance(Double.parseDouble(s.toString()));
                    break;
                case 3:
                    event.setDescription(s.toString());
                    introduceNumTv.setText(length + "/600");
                    break;
                case 4:
                    event.setCost(Integer.parseInt(s.toString()));
                    break;
                case 5:
                    event.setMemberLimit(Integer.parseInt(s.toString()));
                    break;
                case 6:
                    event.setPhoneNumber(s.toString());
                    break;
                }
            } catch (NumberFormatException e) {
            }
        }
    }
}
